#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

int backlog = 10;

enum err
{
    socketerr = 1,
    Binderr,
    Listenerr,

};

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

    int GetSockfd()
    {
        return sockfd_;

    }
    // 创建套接字
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg(FATAL, "Socket error: %d , %s", errno, strerror(errno));
            exit(socketerr);
        }
    }

    // bind
    void Bind(uint16_t port)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        bzero(&peer, len);
        peer.sin_port = htons(port);
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = INADDR_ANY;
        if (bind(sockfd_, (struct sockaddr *)&peer, len) < 0)
        {
            lg(FATAL, "Bind error: %d , %s", errno, strerror(errno));
            exit(Binderr);
        }
    }

    // 监听
    void Listen()
    {
        int n = listen(sockfd_, backlog);
        if (n < 0)
        {
            lg(FATAL, "Listen error: %d , %s", errno, strerror(errno));
            exit(Listenerr);
        }
    }

    // 连接
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        bzero(&peer, len);

        peer.sin_port = htons(port);
        peer.sin_family = AF_INET;
        inet_aton(ip.c_str(), &peer.sin_addr);
        int n = connect(sockfd_, (struct sockaddr *)&peer, len);
        if (n < 0)
        {
            lg(WARNING, "Listen error: %d , %s", errno, strerror(errno));
            return false;
        }
        return true;
    }

    // 接受
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        bzero(&peer, len);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            lg(WARNING, "Accepterror: %d , %s", errno, strerror(errno));
            return -1;
        }

        *clientip = inet_ntoa(peer.sin_addr);
        *clientport = ntohs(peer.sin_port);

        return newfd;
    }

private:
    int sockfd_;
};